﻿using ED.Common.Extensions;
using ED.Cousul;
using Grpc.Net.Client;
using ProtoBuf.Grpc.Client;

namespace ED.GRPC
{
    public class GRPCExtions<T> : IGRPCExtions<T> where T : class
    {
        public IServiceDisConver ServiceDisConver { get; set; }
        public GRPCExtions(IServiceDisConver serviceDisConver)
        {
            ServiceDisConver = serviceDisConver;
        }

        /// <summary>
        /// 获取GRPC服务
        /// </summary>
        /// <param name="grpcUrl">grpcUrl</param>
        /// <returns></returns>
        public async Task<T> GetService(string serviceName)
        {
            var grpcServiceModel = await ServiceDisConver.GetService(serviceName);
            if (grpcServiceModel.IsDefault() || grpcServiceModel.IP.IsNotNullOrEmpty())
            {
                return null;
            }
            GrpcClientFactory.AllowUnencryptedHttp2 = true;
            string address = grpcServiceModel.IP+":"+ grpcServiceModel.Port;
            var channel = GrpcChannel.ForAddress($"http://{address}");
            var service = channel.CreateGrpcService<T>();
            return service;
        }
    }
}
